package com.ezlcp.log.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ezlcp.commons.base.db.BaseDao;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.dto.LoginLog;
import com.ezlcp.commons.service.impl.SuperServiceImpl;
import com.ezlcp.commons.tool.DateUtils;
import com.ezlcp.log.mapper.LoginLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * [用户登录日志]业务服务类
 */
@Service
public class LoginLogServiceImpl extends SuperServiceImpl<LoginLogMapper, LoginLog> implements BaseService<LoginLog> {
    @Autowired
    private LoginLogMapper loginLogMapper;

    /***
     * @description 退出登录，写登出时间
     * @param userId 登录用户ID
     * @param clientType 客户端类型
     * @return java.lang.Boolean
     * @author Elwin ZHANG
     * @date 2023/1/17 15:53
     */
    public Boolean logOut(String userId, Short clientType) {
        //先查出最近一次登录日志
        QueryWrapper<LoginLog> wrapper = new QueryWrapper<LoginLog>();
        wrapper.lambda().eq(LoginLog::getUserId, userId).eq(LoginLog::getClientType, clientType);
        var date = DateUtils.addDays(new Date(), -1);
        wrapper.lambda().gt(LoginLog::getCreateTime, date).orderByDesc(LoginLog::getCreateTime);
        var list = loginLogMapper.selectList(wrapper);
        if (list == null || list.isEmpty()) {
            return false;
        }
        //更新该条记录
        var log = list.get(0);
        log.setLogoutTime(new Date());
        loginLogMapper.updateById(log);
        return true;
    }

    @Override
    public BaseDao<LoginLog> getRepository() {
        return loginLogMapper;
    }
}